package ru.ifmo.genetics.util;

import org.uncommons.maths.number.NumberGenerator;

import java.util.*;

/**
 * @author Roman Kolganov
 *         03.12.11
 */
public class WeightedValuesNumberGenerator implements NumberGenerator<Integer> {

    private final Iterable<Long> weights;
    private int commonWeight = 0;
    private final Random rng = new Random();

    public WeightedValuesNumberGenerator(Iterable<Long> weights) {
        this.weights = weights;
        for (long weight : weights) {
            commonWeight += weight;
        }
    }

    public Integer nextValue() {
        long scaledProbability = Math.round(Math.floor(rng.nextDouble() * commonWeight));
        int resultIndex = -1;
        int currentWeight = 0;
        Iterator<Long> iterator = weights.iterator();
        while (scaledProbability >= currentWeight) {
            resultIndex++;
            currentWeight += iterator.next();
        }
        return resultIndex;
    }

}
